package com.yate.common.config.exception;

import com.yate.common.result.Result;
import com.yate.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;




/**
 * @ Tool：IntelliJ IDEA
 * @ Author：云生
 * @ Date：2024-11-29-16:55
 * @ Version：1.0
 * @ Description：
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     *@Author: yate
     *@Description:全局异常处理
     *@param:
     *@return:
     */
    @ExceptionHandler(Exception.class)
    public Result error(Exception e){
        e.printStackTrace();
        log.error(e.getMessage(), e);
        return Result.fail().message("执行全局异常处理...");
    }

    /**
     *@Author: yate
     *@Description:特定异常处理
     *@param:
     *@return:
     */
    @ExceptionHandler(ArithmeticException.class)
    public Result error(ArithmeticException e){
        e.printStackTrace();
        log.error(e.getMessage(), e);
        return Result.fail().message("执行特定异常处理...");
    }

    /**
     *@Author: yate
     *@Description:自定义异常处理
     *@param:
     *@return:
     */
    @ExceptionHandler(BusinessException.class)
    public Result error(BusinessException e){
        e.printStackTrace();
        log.error(e.getMessage(), e);
        return Result.fail().code(e.getCode()).message(e.getMessage());
        }


    @ExceptionHandler(NumberFormatException.class)
    public ResponseEntity<Result> handleNumberFormatException(NumberFormatException ex) {
        Result result = new Result();
        result.setMessage("参数格式错误");
        result.setCode(ResultCodeEnum.FAIL.getCode());
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * spring security异常
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result error(AccessDeniedException e) throws AccessDeniedException {
        return Result.fail().code(205).message("无权限访问");
    }

}
